<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\WorkRoom\Listener;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use MoChat\App\WorkRoom\Contract\WorkRoomContract;
use MoChat\App\WorkRoom\Event\DismissRoomRawEvent;
use Psr\Container\ContainerInterface;

/**
 * 客户群解散事件
 * 当客户群被群主解散后，回调该事件。
 * 需注意的是，如果发生群信息变动，会立即收到此事件，但是部分信息是异步处理，
 * 可能需要等一段时间(例如2秒)调用获取客户群详情接口才能得到最新结果.
 *
 * @Listener(priority=9999)
 */
class DismissRoomRawListener implements ListenerInterface
{
    /**
     * @Inject
     * @var WorkRoomContract
     */
    protected $workRoomService;

    /**
     * @Inject
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var StdoutLoggerInterface
     */
    private $logger;

    public function listen(): array
    {
        return [
            DismissRoomRawEvent::class,
        ];
    }

    /**
     * @param DismissRoomRawEvent $event
     */
    public function process(object $event)
    {
        try {
            $this->logger = $this->container->get(StdoutLoggerInterface::class);
            $this->workRoomService->deleteWorkRoomByWxChatId($event->message['ChatId']);
        } catch (\Throwable $e) {
            $this->logger->error(sprintf('[客户群解散事件]监听失败，错误信息: %s', $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
        }
    }
}
